import requests
import os
import time
class getBILBIL:

    def __init__(self):
        # current_path = os.getcwd()
        # print("当前路径为：%s" % current_path)
        param = ''
        f = open('room.txt', 'r', encoding='utf-8')
        num = f.read()
        f.close()
        param = num.split(',')
        url = 'https://api.live.bilibili.com/room/v1/Room/room_init'
        # param = {'id': '22603245'}
        # startNow =''
        self.headerss = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.36'}

        self.Arry = []
        for i in param:
            params = {'id': i}
            # print(params)
            with requests.Session() as s:
                htmlOne = requests.get(url,headers=self.headerss,params=params).json()
                # time.sleep(0.25)
                if htmlOne['msg'] == '直播间不存在':
                    raise Exception(f'bilibili {htmlOne} {htmlOne["msg"]}')
                live_status = htmlOne['data']['live_status']
                self.real_room_id = htmlOne['data']['room_id']
                if live_status != 1:
                    # startNow = '直播间未开播'
                    print('|False',end="")
                    # self.Arry.append('|False')
                    # raise Exception(f'bilibili {htmlOne} 未开播')
                else:
                    # startNow = '直播间已播'
                    self.getUrl()

    def getUrl(self) -> dict:
        url = 'https://api.live.bilibili.com/xlive/web-room/v2/index/getRoomPlayInfo'
        current_qn = 10000
        param = {
            'room_id': self.real_room_id,
            'protocol': '0,1',
            'format': '0,1,2',
            'codec': '0,1',
            'qn': current_qn,
            'platform': 'h5',
            'ptype': 8,
        }
        res = requests.get(url, headers=self.headerss, params=param).json()
        # print(res['data'])
        stream_info = res['data']['playurl_info']['playurl']['stream']
        qn_max = 0

        stream_urls = {}
        for D in stream_info:
            if D['protocol_name'] == 'http_hls':
                base_url = D['format'][0]['codec'][0]['base_url']
                url_info = D['format'][0]['codec'][0]['url_info']

                for index,Url in enumerate(url_info):
                    host = Url['host']
                    extra = Url['extra']
                    stream_urls = f'{host}{base_url}{extra}'
                    # {self.real_room_id,True}
                # return stream_urls
                # print({f'room':self.real_room_id},stream_urls)
                print('|'+stream_urls,end="")
                # self.Arry.append(stream_urls)
            # print(self.Arry)
            # else:
                # print('直播源格式已切换，请重新编写','当前格式',{D['protocol_name']})
                # return
        # return self.Arry
        # print('|'.join(self.Arry))
        

if __name__ == "__main__":
    getBli = getBILBIL()